package com.cloud.serviceverificationcode.service.impl;

import com.cloud.serviceverificationcode.service.VerifyService;
import com.cloud.internalcommon.dto.ResponseResult;
import com.cloud.internalcommon.dto.serviceverificationcode.VerifyCodeResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service

public class VerifyServiceImpl implements VerifyService {

    private static final String VERIFY_PREFIX="VERIFY_PHONE_NUMBER_";

    @Autowired
    StringRedisTemplate redisTemplate;

    /**
     * 生成验证码，保存到redis中，并返回验证码
     * @param identity 身份
     * @param phoneNumber 手机号码
     * @return 相应实例
     */
    @Override
    public ResponseResult<VerifyCodeResponse> generate(int identity, String phoneNumber) {
        String code = String.valueOf((int) ((Math.random() * 9 - 1) * Math.pow(10, 5)));

        //将验证码放到redis中，并设置2分钟过期
        BoundValueOperations<String, String> redis_key_phone_number = redisTemplate.boundValueOps(VERIFY_PREFIX + phoneNumber);
        redis_key_phone_number.set(code,2, TimeUnit.MINUTES);

        VerifyCodeResponse data = new VerifyCodeResponse().setCode(code);
        return ResponseResult.success(data);
    }

    /**
     * 验证验证码
     * @param phoneNumber 手机号码
     * @param code 验证码
     * @return 验证结果
     */
    @Override
    public ResponseResult<?> verify(String phoneNumber, String code) {
        //redis中取出验证码
        BoundValueOperations<String, String> redis_key_phone_number = redisTemplate.boundValueOps(VERIFY_PREFIX + phoneNumber);
        String old_code = redis_key_phone_number.get();
        if (code != null && code.equals(old_code)){
            return ResponseResult.success();
        }
        return ResponseResult.fail();
    }

}
